<template>
  <div class="strut-div">
    <div class="mt-card">
      <span class="selectvalue">{{displayName}} <img src="../../../assets/imgs/jxwy/arrow.png" /> </span>
      <select class="select" @change="handleChange" :value="value">
        <option v-for="item in options" :value="item.code" :key="item.code">{{item.name}}</option>
      </select>
      <div class="pic">
        <div class="box" v-for="(node, index) in monitor.list" :key="node.code">
          <div class="video">
            <video :id="`video${node.code}`" class="video video-js vjs-default-skin vjs-big-play-centered" :poster="posters[index % 2]">
              <source :src="node.url" type="application/x-mpegURL"/>
            </video>
          </div>
          <button>{{node.name}}</button>
          <a @click="handleMask(node)"><img src="../../../assets/imgs/jxwy/big.png" /></a>
        </div>
      </div>
      <div class="card-pager">
        <button v-show="monitor.page !== 1" title="上一页" class="pager prev" @click="handlePage">&lt;</button>
        <button v-show="monitor.page < monitor.totalPage" title="下一页" class="pager next" @click="handlePage">&gt;</button>
      </div>
      <div class="card-item speCard">
        <p class="card-title middle-title">2019年育苗种类统计</p>
        <div class="card-div">
          <div class="split-line">
            <div class="dot" />
            <div class="line" />
            <div class="dot" />
          </div>
          <div class="percent-wrap">
            <div class="percent-box" v-for="(data, index) in pieData">
              <common-cyclic-chart :ref="`pie${index}`" :config="data" />
              <div class="percent-txt">{{data.name}}</div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="!!video.url" class="camera-mask">
        <div class="mask-title">{{video.name}}<a @click="handleCloseMask()">×</a></div>
        <div class="video-wrap">
          <video :id="`video${video.code}`" class="video video-js vjs-default-skin vjs-big-play-centered" :poster="posters[0]">
            <source :src="video.url" type="application/x-mpegURL" />
          </video>
        </div>
      </div>
    </div>
    <div class="mb-card">
      <div class="card-item season" style="height:180px;width: 100%;">
        <div v-for="item in seasonEnvironment" class="season-item">
          <div>
            <div class="season-label">{{item.title}}</div>
            <div class="season-content">
              <p v-for="(key, index) in item.keys">
                <span>{{key}}：</span>
                {{item.values[index]}}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {getMonitors, getRegions, growPieData, seasonEnvironment, topTotalData} from '@/network/tg-fake-data.js'
  import CommonCyclicChart from '@/components/common/common-cyclic-chart.vue';
  import videojs from 'video.js';
  // import 'videojs-flash';
  // window.videojs = videojs;
  // videojs.options.flash.swf = 'static/video-js.swf';

  // 配色数据
  const colors = [['#1046F6', '#0DFCF6', '#00C4FF'], ['#FF8400', '#FFFC1B', '#FFAC09']];
  // 饼图原始数据
  const pieData = growPieData.map(([name, value], index) => {
    // 前四个使用配色1，后四个使用配色2
    const [ startColor, endColor, txtColor ] = index < 4 ? colors[0] : colors[1];
    return {
      name,
      color: txtColor,
      option: {
        id: `pie${index}`,
        txtColor,
        startColor,
        endColor,
        value,
      },
    };
  });
  // 视频下拉
  const videos = ['巨鑫伟业', '五谷精装', '果科所', '晋宏农商品合作社', '番茄小镇', '宝成药厂', '广誉远', '田森', '怡园酒庄'];
  // 已经加载的视频列表
  let vList = [];
  // 默认封面
  const posters = [
    require('../../../assets/imgs/jxwy/address1.png'),
    require('../../../assets/imgs/jxwy/address2.png')
  ];

  export default {
    name: 'sxMiddle',
    components: {
      CommonCyclicChart,
    },
    mounted() {
      // 初始化饼图
      Object.keys(this.$refs).filter(key => key.startsWith('pie'))
      .forEach(key => this.$refs[key][0].initChart());
      // 获取园区，下一步再初始化监控
      getRegions({ page: 1, size: 10 }).then(({ list = [] }) => {
        this.options = list.filter(item => item.parentIndexCode !== '-1').map(item => ({
          name: item.name,
          code: item.indexCode,
        }));
        if (this.options.length) {
          const [ first ] = this.options;
          this.value = first.code;
          // 初始化监控，默认请求第一页
          this.fetchMonitor();
        } else {
          this.$alert('未接入任何园区或未找到监控信息！')
        }
      });
    },
    data() {
      return {
        options: videos.map(item => ({
          name: item,
          code: item.code,
        })),
        value: '',
        topTotalData: topTotalData,
        pieData,
        seasonEnvironment,
        // 监控视频指示
        monitor: {
          list: [],
          page: 1,
          total: 0,
          totalPage: 0
        },
        // 当前放大的视频
        video: {
          name: "",
          url: "",
          code: "",
          instance: null,
        },
        posters,
      }
    },
    computed: {
      displayName() {
        if (this.value && this.options.length) {
          const found = this.options.find(item => item.code === this.value);
          return found && found.name || '巨鑫伟业';
        }
        return '巨鑫伟业';
      }
    },
    methods: {
      fetchMonitor(page = 1) {
        // 请求监控探头
        getMonitors({ page, regionCode: this.value }).then(({ list, total }) => {
          this.monitor = {
            list,
            total,
            page,
            totalPage: Math.floor(total / 2) + (total % 2 === 1 ? 1 : 0),
          };
          this.$nextTick(() => {
            this.initVideos();
          });
        }).catch(e => this.$alert(e));
      },
      // 改变视频的回调
      handleChange(e) {
        const { target: { value } } = e;
        this.value = value;
        this.$emit('video-change',value);
        // 先销毁videos
        this.clearVideo();
        this.fetchMonitor();
      },
      // 处理分页
      handlePage(e) {
        const { target: { className } } = e;
        const { page } = this.monitor;
        if (className.includes('prev')) {
          this.clearVideo();
          this.fetchMonitor(page - 1);
        } else {
          this.clearVideo();
          this.fetchMonitor(page + 1);
        }
      },
      initVideos() {
        console.log('初始化了视频！');
        vList = this.monitor.list.map(({ code, url }) => this.createVideo(code, url));
      },
      createVideo(id, url, w = 310, h = 228) {
        return videojs(`video${id}`, {
          controls: false,
          autoplay: 'muted',
          hls: {
            withCredentials: true
          },
          techCanOverridePoster: true,
          preload: "auto",
          width: w,
          height: h,
          controlBar: { // 配置控制栏
            timeDivider: false, // 时间分割线
            durationDisplay: false, // 总时间
            progressControl: true, // 进度条
            customControlSpacer: false, // 未知
            fullscreenToggle: false, // 全屏
          },
        });
      },
      clearVideo() {
        vList.forEach(v => {
          try {
            v.dispose()
          } catch (e) {
            console.error(e);
          }
        });
        if (this.video.instance) {
          this.video.instance.dispose();
        }
      },
      handleMask(node) {
        if (this.video.instance) {
          this.video.instance.dispose();
        }
        this.video = {
          ...node,
          code: `mask${node.code}`,
        };
        this.$nextTick(() => {
          this.video.instance = this.createVideo(this.video.code, this.video.url, 805, 450);
        });
      },
      handleCloseMask() {
        this.video.instance.dispose();
        this.video = {
          name: '',
          url: '',
          code: '',
          instance: null,
        };
      }
    },
    beforeDestroy() {
      this.clearVideo();
    },
  }
</script>

<style lang="scss">
  .mt-card {
    width: 100%;
    height: 750px;
    position: relative;
    // background: url(../../../assets/imgs/tg/middle-card.png) no-repeat;
  }

  .mb-card {
    margin-top: 20px;
  }

  .select {
    width: 350px;
    display: block;
    margin: 0 auto;
    padding: 0 2%;
    height: 64px;
    border: none;
    outline: none;
    line-height: 64px;
    text-align: center;
    text-align-last:center;
    background: url(../../../assets/imgs/jxwy/bg.png) no-repeat;
    position: relative;
    top: 0;
    color: rgba(0, 0, 0, 0);

    option {
      display: flex;
      justify-content: center;
      align-items: center;
      color: white !important;
      font-size: 16px !important;
      background: #002450;
      border: none;
      text-align: center;
      height: 20px;
      line-height: 20px;
      &:before, &:after {
        color: black !important;
        font-size: 18px !important;
      }
    }
  }

  .selectvalue {
    display: inline-block;
    position: relative;
    width: 350px;
    top: 42px;
    left: 36%;
    text-align: center;
    font-size: 17px;
  }

  .selectvalue img {
    width: 18px;
    position: relative;
    top: 3px;
  }

  .pic {
    position: relative;
    top: 30px;
    text-align: center;
    height: 370px;
  }

  .pic .box {
    display: inline-block;
    min-height: 280px;
    margin-right: 50px;
    &:last-child {
      margin-right: 0;
    }
  }

  .pic .box .video {
    width: 510px;
    height: 330px;
  }

  .pic .box >button {
    display: inline-block;
    background-color: rgba(0, 150, 255, 0.4);
    min-width: 100px;
    height: 38px;
    color: #ffffff;
    font-size: 14px;
    border: none;
    float: left;
    margin-top: 10px;
    border-radius: 3px;
  }

  .pic .box a {
    display: inline-block;
    cursor: pointer;
    background-color: rgba(0, 150, 255, 0.4);
    width: 38px;
    height: 38px;
    color: #ffffff;
    font-size: 14px;
    border: none;
    text-align: center;
    float: right;
    margin-top: 10px;
    border-radius: 3px;
  }

  .pic .box a img {
    width: 20px;
    height: 20px;
    position: relative;
    top: 9px;
  }

  .speCard {
    position: relative;
    top: 50px;
    height: 200px;
    width: calc(100%);
    // left: 39px;
    background: rgba(0, 0, 0, 0);
  }

  .speCard .card-title {
    text-align: center;
    background: rgba(23, 108, 160, .4);
  }

  .speCard.card-item::before {
    background: transparent !important;
  }
  .middle-title {
    width: calc(100% - 400px);
    margin: 20px 200px 0 200px !important;
    padding: 0 !important;
    line-height: 48px;
    background: rgba(0, 150, 255, 0.4) !important;
    color: #00E2FF;
  }

  .split-line {
    width: calc(100% - 380px);
    height: 5px;
    display: flex;
    margin: 15px 190px 0 190px;

    div {
      display: inline-block;
    }
    .dot {
      width: 5px;
      height: 5px;
      background: rgba(0, 174, 255, 1);
    }
    .line {
      width: calc(100% - 10px);
      height: 1px;
      background: rgba(0, 174, 255, 1);
      opacity: 0.45;
    }
  }

  .percent-wrap {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    height: calc(100% - 10px);



    /*显示百分比的box*/
    .percent-box {
      width: calc(12.5%);
      height: 80%;
      // margin: 5px 0 0 5px;
      text-align: center;
      position: relative;
      /*每当4n的元素，拼接右侧间距，保证间距一致*/


      .percent-txt {
        // margin-top: -18px;
        color: white;
      }
    }
  }
  .season {
    &::before {
      background: none !important;
    }
    .season-item {
      float: left;
      width: calc(25% - 40px);
      height: 150px;
      padding: 20px 0 0 32px;

      >div {
        width: 100%;
        height: 100%;
        background: url(../../../assets/imgs/jxwy/season.png) no-repeat;
        background-size: 100% 100%;
        .season-label {
          display: inline-block;
          float: left;
          position: relative;
          font-size: 20px;
          width: 120px;
          height: 120px;
          line-height: 120px;
          text-align: center;
        }
        .season-content {
          float: left;
          display: inline-block;
          width: calc(100% - 120px);
          height: 100%;
          font-size: 15px;
          padding-top: 35px;
          line-height: 36px;
          >p {
            color: #FFD200;
            font-weight: bold;
            span {
              color: white;
              font-weight: normal;
            }
          }
        }
      }
    }
  }
  /*视频蒙版*/
  .camera-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 700px;
    background-color: rgba(14,44,74,0.9) !important;
    .video-wrap {
      height: 650px;
    }
    .video {
      width: 100%;
      height: 100%;
    }
    .mask-title {
      height: 50px;
      text-align: center;
      font-size: 20px;
      line-height: 50px;
      a {
        position: absolute;
        cursor: pointer;
        top: 0;
        right: 0;
        font-size: 30px;
        line-height: 50px;
        width: 50px;
        height: 50px;
      }
    }
  }
  /*分页控件*/
  .card-pager {
    position: absolute;
    top: 29%;
    text-align: center;
    width: 100%;
    .pager {
      width: 39px;
      height: 39px;
      cursor: pointer;
      background-color: rgba(0, 150, 255, 0.4);
      color: #ffffff;
      font-size: 14px;
      border: none;
      border-radius: 3px;
      &.disabled {
        display: none;
      }
      &.prev {
        float: left;
        margin-left: 28px;
      }
      &.next {
        float: right;
        margin-right: 28px;
      }
    }
  }
</style>
